
import { JFramer } from "./JFramer";
import { StoreManager } from "../Managers/StoreManager";
import { ArrayUtility } from "../Utility/ArrayUtility";
import { FDispose } from "../Support/FDispose";

export class JFrameStacker extends FDispose
{
    public static ClassName:string = "JFrameStacker";
	private framer:JFramer;
    private frames:any[] = [];
    private isStart:Boolean = false;
    public constructor()
    {
        super();
        // this.isCanStore = true;
    }

    public addFrame(frame:number,thisObj:any,fun:Function,...args):void
    {
        this.stop();
        this.frames.push({obj:thisObj,frame:frame,fun:fun,args:args});
    }
    public start():void
    {
        if(this.isStart)return;
        ArrayUtility.SortOn(this.frames,"frame");
        this.isStart = true;
        if(this.framer==null)
        {
            this.framer = JFramer.GetFramer();
            this.framer.addFramerCallback(this,this.onFrame);
            this.framer.name = "JFrameStacker";
        }
        this.framer.start();
        this.tickTriggerFrame();
    }
    private onFrame():void
    {
        this.tickTriggerFrame();
    }
    private tickTriggerFrame():void
    {
        for(let i:number = 0;i<frames.length;i++)
        {
            if(frames[i].frame==this.framer.frame)
            {
                let o:any = frames[i];
                this.frames.splice(i,1);
                if(o.fun)o.fun.call(o.obj,o.args);
                i--;
            }
        }
        if(frames.length==0)stop();
    }
    public stop():void
    {
        if(!this.isStart)return;
        this.isStart = false;
        this.framer&&this.framer.stop();
    }
    public dispose():void
    {
        this.stop();
        this.frames.length = 0;
        this.framer&&this.framer.dispose();
        this.framer = null;
        super.dispose();
    }
    public static GetFramer():JFrameStacker{return StoreManager.New(JFrameStacker);}
}
